/*
 * Created by JFormDesigner on Mon Jun 21 18:27:45 GMT+08:00 2021
 */

package com.bk.view;

import java.awt.event.*;
import com.bk.dao.BookDao;
import com.bk.dao.BorrowDao;
import com.bk.dao.UserDao;
import com.bk.model.Book;
import com.bk.model.User;
import com.bk.util.ToolUtil;

import java.awt.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Vector;
import javax.swing.*;
import javax.swing.GroupLayout;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

/**
 * @author Ayi
 */
public class UserFrame extends JFrame {
    User user;
    private DefaultTableCellRenderer dr;

    public UserFrame(User user) {
        this.user = user;
        dr = new DefaultTableCellRenderer();
        initComponents();
        try {
            setBooks();
            setBorrow();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException classNotFoundException) {
            classNotFoundException.printStackTrace();
        }
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }


    // 初始化图书表
    public void setBooks() throws SQLException, ClassNotFoundException {
        // 重定义模型
        Vector<Vector<String>> vtBook = new Vector<Vector<String>>();
        Vector<String> headBook = new Vector<String>();
        headBook.add("图书id");
        headBook.add("书名");
        headBook.add("类型");
        headBook.add("余量");
        DefaultTableModel bookTableModel = new DefaultTableModel(vtBook, headBook);
        table1.setModel(bookTableModel);
        // 从数据库取表
        ResultSet bt = new BookDao().getBookTable();
        // 初始化UI表内数据
        while (bt.next()) {
            Vector<String> temp = new Vector<String>();
            temp.add(bt.getString("bid"));
            temp.add(bt.getString("bname"));
            temp.add(bt.getString("btype"));
            temp.add(bt.getString("binventory"));
            vtBook.add(temp);
        }
        dr.setHorizontalAlignment(JLabel.CENTER);
        table1.setDefaultRenderer(Object.class, dr);
        scrollPane1.updateUI();
    }

    // 初始化借阅表
    public void setBorrow() throws SQLException, ClassNotFoundException {
        // 重定义模型
        Vector<Vector<String>> bro = new Vector<Vector<String>>();
        Vector<String> headBro = new Vector<String>();
        headBro.add("图书id");
        headBro.add("书名");
        headBro.add("类型");
        headBro.add("借阅量");
        headBro.add("借阅时间");
        headBro.add("期限剩余");
        DefaultTableModel bookTableModel = new DefaultTableModel(bro, headBro);
        table2.setModel(bookTableModel);
        // 从数据库取表
        ResultSet bt = new BorrowDao().getBorrowTable(user);
        // 初始化UI表内数据
        int booknums = 0;
        while (bt.next()) {
            Vector<String> temp = new Vector<String>();
            temp.add(bt.getString("bid"));
            temp.add(bt.getString("bname"));
            temp.add(bt.getString("btype"));
            temp.add(bt.getString("uborrow"));
            temp.add(bt.getString("starttime"));
            temp.add(bt.getString("deadlinetime"));
            bro.add(temp);
            booknums += Integer.valueOf(bt.getString("uborrow"));
        }
        dr.setHorizontalAlignment(JLabel.CENTER);
        table2.setDefaultRenderer(Object.class, dr);
        // 计算用户总借阅量，更新到用户表
        new UserDao().updateBooknums(user, booknums);
        scrollPane2.updateUI();
    }

    // 刷新
    private void button3ActionPerformed(ActionEvent e) {
        // TODO add your code here
        try {
            try {
                this.user = new BorrowDao().updateDeadlineTime(user);
                setTitle("欢迎您，" + user.getUname() + "，这里是借阅端（当前信用：" + user.getUcredit() + "）");
            } catch (ParseException parseException) {
                parseException.printStackTrace();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            setBooks();
            setBorrow();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ClassNotFoundException classNotFoundException) {
            classNotFoundException.printStackTrace();
        }
    }

    // 你是一个黑名单用户吗？
    public boolean areYouABlackUser() {
        try {
            String answer = new UserDao().searchInBlackList(user.getUid()) == true ? "Yes" : "No";
            if (answer.equals("Yes")) {
                JOptionPane.showMessageDialog(null, "您被管理员加入了黑名单，并强制下线");
                return true;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }

    // 借阅 监听
    private void button1ActionPerformed(ActionEvent e) {
        // TODO add your code here
        button3.doClick();
        if (areYouABlackUser()) {
            dispose();
            return;
        }
        if (user.getUcredit().equals("较差") || user.getUcredit().equals("非常差")) {
            JOptionPane.showMessageDialog(null, "您当前信用较低，借阅通道已关闭");
            return;
        }
        // 查找
        String idOrNameInfo = JOptionPane.showInputDialog(null, "请输入图书id或书名", "借阅", 1);
        Book book = null;
        if (idOrNameInfo != null) {
            boolean bool = new ToolUtil().judgeIdOrName(idOrNameInfo);
            if (bool) {
                try {
                    book = new BookDao().searchBookById(idOrNameInfo);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }else{
                try {
                    book = new BookDao().searchBookByName(idOrNameInfo);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (book == null) {
                JOptionPane.showMessageDialog(null, "找不到这本书");
                return;
            }
        }else {
            return;
        }
        // 借阅
        try {
            if (new BorrowDao().addBorrowTable(user, book)) {
                JOptionPane.showMessageDialog(null, "借阅成功");
            }else{

            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        button3.doClick();
    }

    // 退订 监听
    private void button2ActionPerformed(ActionEvent e) {
        // TODO add your code here
        if (areYouABlackUser()) {
            dispose();
            return;
        }
        String idOrNameInfo = JOptionPane.showInputDialog(null, "请输入图书id或书名", "退订", 1);
        Book book = null;
        if (idOrNameInfo != null) {
            boolean bool = new ToolUtil().judgeIdOrName(idOrNameInfo);
            if (bool) {
                try {
                    book = new BookDao().searchBookById(idOrNameInfo);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }else{
                try {
                    book = new BookDao().searchBookByName(idOrNameInfo);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (book == null) {
                JOptionPane.showMessageDialog(null, "找不到这本书");
                return;
            }
        }else {
            return;
        }
        try {
            if (new BorrowDao().deleteBorrowTable(idOrNameInfo, book)) {
                JOptionPane.showMessageDialog(null, "退订成功");
            }else{
                JOptionPane.showMessageDialog(null, "退订失败，您可能没有借这本书");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        button3.doClick();
    }

    // 退出登录，监听
    private void button4ActionPerformed(ActionEvent e) {
        // TODO add your code here
        new LoginFrame().setVisible(true);
        dispose();
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        // Generated using JFormDesigner Evaluation license - unknown
        scrollPane1 = new JScrollPane();
        table1 = new JTable();
        scrollPane2 = new JScrollPane();
        table2 = new JTable();
        button1 = new JButton();
        button2 = new JButton();
        button3 = new JButton();
        button4 = new JButton();

        //======== this ========
        setTitle(" ");
        setIconImage(new ImageIcon(getClass().getResource("/images/main.png")).getImage());
        setBackground(Color.white);
        setResizable(false);
        Container contentPane = getContentPane();

        //======== scrollPane1 ========
        {

            //---- table1 ----
            table1.setEnabled(false);
            scrollPane1.setViewportView(table1);
        }

        //======== scrollPane2 ========
        {

            //---- table2 ----
            table2.setEnabled(false);
            scrollPane2.setViewportView(table2);
        }

        //---- button1 ----
        button1.setText("\u501f\u9605");
        button1.setBackground(Color.white);
        button1.setFont(new Font("\u5fae\u8f6f\u96c5\u9ed1", Font.PLAIN, 12));
        button1.addActionListener(e -> button1ActionPerformed(e));

        //---- button2 ----
        button2.setText("\u9000\u8ba2");
        button2.setBackground(Color.white);
        button2.setFont(new Font("\u5fae\u8f6f\u96c5\u9ed1", Font.PLAIN, 12));
        button2.addActionListener(e -> button2ActionPerformed(e));

        //---- button3 ----
        button3.setText("\u5237\u65b0");
        button3.setBackground(Color.white);
        button3.setFont(new Font("\u5fae\u8f6f\u96c5\u9ed1", Font.PLAIN, 12));
        button3.addActionListener(e -> button3ActionPerformed(e));

        //---- button4 ----
        button4.setText("\u9000\u51fa\u767b\u5f55");
        button4.setBackground(Color.white);
        button4.setFont(new Font("\u5fae\u8f6f\u96c5\u9ed1", Font.PLAIN, 12));
        button4.addActionListener(e -> button4ActionPerformed(e));

        GroupLayout contentPaneLayout = new GroupLayout(contentPane);
        contentPane.setLayout(contentPaneLayout);
        contentPaneLayout.setHorizontalGroup(
            contentPaneLayout.createParallelGroup()
                .addGroup(contentPaneLayout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(contentPaneLayout.createParallelGroup()
                        .addComponent(scrollPane1, GroupLayout.DEFAULT_SIZE, 890, Short.MAX_VALUE)
                        .addComponent(scrollPane2, GroupLayout.DEFAULT_SIZE, 890, Short.MAX_VALUE))
                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
                        .addComponent(button2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(button3, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(button1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(button4, GroupLayout.PREFERRED_SIZE, 95, GroupLayout.PREFERRED_SIZE))
                    .addContainerGap())
        );
        contentPaneLayout.setVerticalGroup(
            contentPaneLayout.createParallelGroup()
                .addGroup(contentPaneLayout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(contentPaneLayout.createParallelGroup()
                        .addGroup(contentPaneLayout.createSequentialGroup()
                            .addComponent(button1)
                            .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(button2)
                            .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(button3))
                        .addComponent(scrollPane1, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(contentPaneLayout.createParallelGroup()
                        .addComponent(scrollPane2, GroupLayout.Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, 245, GroupLayout.PREFERRED_SIZE)
                        .addComponent(button4, GroupLayout.Alignment.TRAILING))
                    .addContainerGap())
        );
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents
    }

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
    // Generated using JFormDesigner Evaluation license - unknown
    private JScrollPane scrollPane1;
    private JTable table1;
    private JScrollPane scrollPane2;
    private JTable table2;
    private JButton button1;
    private JButton button2;
    private JButton button3;
    private JButton button4;
    // JFormDesigner - End of variables declaration  //GEN-END:variables
}
